//
//  NetworkManager.m
//  
//
//  Created by MT on 2017/11/18.
//  Copyright © 2017年 MT. All rights reserved.
//

#import "NetworkManager.h"

@implementation NetworkManager

+ (void)get:(NSString *)url parameters:(id)params success:(void (^)(id object))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)post:(NSString *)uri parameters:(NSDictionary *)parameters success:(void (^)(id object))success failure:(void (^)(NSError *error))failure
{
    NSAssert(success && failure, @"holy shit");
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer.timeoutInterval = 15.f;
    
    NSMutableDictionary * totalParameters = [self getTotalParameters:parameters];
    NSString *urlString = (uri.length == 0) ? kDefaultServerURL : [NSString stringWithFormat:@"%@%@", kServerURL, uri];
    [manager POST:urlString parameters:totalParameters progress:nil success:^(NSURLSessionDataTask *task, id response) {
        DebugLog(@"请求成功, api = %@, response = %@", uri, [Tool DataTOjsonString:response]);
        if ([response[@"status"] integerValue] == 1) {
            // 正确的结果
            success(response[@"data"]);
        }else if ([response[@"status"] integerValue] == 3007) {
            // 正确的结果
            success(response);
        }else if ([response[@"status"] integerValue] == 3008) {
            // 正确的结果
            success(response);
        }else {
            // 非正确的结果，当错误返回，UIViewController+Addition里统一处理
            NSError *error = [self errorWithDescription:response[@"msg"] code:[response[@"status"] integerValue] ];
            failure(error);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DebugLog(@"请求失败, api = %@, error = %@", uri, error);
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark - Helper
+ (NSMutableDictionary *)getTotalParameters:(NSDictionary *)parameters
{
    NSMutableDictionary *totalParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
    totalParameters[@"sn"] = [Tool currentTimeStr];
    totalParameters[@"pv"] = @"ios";
    totalParameters[@"v"] = AppVersion;
    NSString *token = [Tool getLocalDataValue:kAccessTokenKey];
    if (token) {
        totalParameters[@"token"] = token;
    }
    totalParameters[@"sign"] = [Tool sortSign:totalParameters];
    
    return totalParameters;
}

+ (NSError *)errorWithDescription:(NSString *)description code:(NSInteger)code
{
    return [NSError errorWithDomain:NSCocoaErrorDomain
                               code:code
                           userInfo:@{NSLocalizedDescriptionKey: description}];
}

@end
